<template>
  <section :key="uniqueProject" class="diseasesHealth">
    <div class="operate">
      <ElButton type="primary" round plain @click="upMassagetPrice"
        >保存修改</ElButton
      >
      <!--
      <ElUpload
        class="up-excel-button"
        :action="url.excel"
        :headers="headers"
        :show-file-list="false"
        name="excel"
        :on-success="upExcelSuccess"
        :on-error="upExcelError"
      >
        <ElButton type="primary" round plain>批量导入</ElButton>
      </ElUpload>
      -->
      <ElButton type="primary" round plain @click="exportExcel"
        >导出表格</ElButton
      >
      <!--
      <ElButton type="primary" round plain @click="getTemplate"
        >下载模板</ElButton
      >
      -->
    </div>
    <MemberSelector
      class="members"
      :no-members.sync="noMembers"
      @selected="filter"
    />
    <ElTable
      :class="{noMembers: noMembers}"
      :data="showSpecialItems"
      :stripe="true"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <ElTableColumn align="center" type="selection" width="60">
      </ElTableColumn>
      <ElTableColumn
        align="center"
        prop="commodity_name"
        width="130"
        label="项目名称"
      >
      </ElTableColumn>
      <ElTableColumn
        v-if="priceLevel.length > 0"
        align="center"
        prop="price_primary"
        min-width="180"
        label="高级服务"
      >
        <template slot-scope="scope">
          <ElInput
            v-model="scope.row.price.price_primary"
            placeholder="0"
            class="input"
            @change="changeEditStatus"
            >{{ scope.row.price.price_primary }}</ElInput
          >元/次
        </template>
      </ElTableColumn>
      <ElTableColumn
        v-if="priceLevel.length > 1"
        align="center"
        prop="price_advanced"
        min-width="180"
        label="特级服务"
      >
        <template slot-scope="scope">
          <ElInput
            v-model="scope.row.price.price_advanced"
            placeholder="0"
            class="input"
            @change="changeEditStatus"
            >{{ scope.row.price.price_advanced }}</ElInput
          >元/次
        </template>
      </ElTableColumn>
      <ElTableColumn
        v-if="priceLevel.length > 2"
        align="center"
        prop="price_chief"
        min-width="180"
        label="首席服务"
      >
        <template slot-scope="scope">
          <ElInput
            v-model="scope.row.price.price_chief"
            placeholder="0"
            class="input"
            @change="changeEditStatus"
            >{{ scope.row.price.price_chief }}</ElInput
          >元/次
        </template>
      </ElTableColumn>
      <ElTableColumn align="center" prop="methods" min-width="180" label="操作">
        <template slot-scope="scope">
          <ElButton
            size="medium"
            plain
            type="primary"
            round
            @click="handleDelete(scope.row)"
            >删除</ElButton
          >
          <ElButton
            size="medium"
            plain
            type="primary"
            round
            @click="handleEdit(scope.row.id)"
            >编辑</ElButton
          >
        </template>
      </ElTableColumn>
    </ElTable>
    <ElPagination
      v-if="specialItems.length > 20"
      :current-page.sync="currentPage"
      :page-size="pageSize"
      :page-sizes="pageSizes"
      layout="sizes, prev, pager, next"
      :total="specialItems.length"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </ElPagination>
  </section>
</template>

<script>
import _ from 'lodash';
import Cookie from 'js-cookie';
import {http, catchAppError} from '@/util';
import url from '@/config';
import {pageSizes, menusNavigation} from '@/store';
import MemberSelector from './MemberSelector.vue';
import toast from '@/toast';
import changeEditStatus from './ProjectEditStatus';

export default {
  name: 'SpecialItems',
  components: {MemberSelector},
  data() {
    return {
      url,
      uniqueProject: 0,
      pageSize: 20,
      currentPage: 1,
      pageSizes,
      priceLevel: [],
      headers: {
        token: Cookie.get('token')
      },
      noMembers: true,
      params: {
        shop_type: 7,
        grade_id: null
      },
      specialItems: [],
      showSpecialItems: [],
      multipleSelection: []
    };
  },
  beforeMount() {
    this.getSpecialItems();
    this.getPriceLevel();
  },
  updated() {
    changeEditStatus(false);
  },
  methods: {
    changeEditStatus,
    getPriceLevel() {
      http
        .get(url.masseurLevel)
        .then(res => {
          this.priceLevel = res;
        })
        .catch(catchAppError);
    },
    handleSelectionChange(val) {
      this.multipleSelection[this.currentPage - 1] = val;
    },
    getTemplate() {
      http
        .post(url.getTemplate, {type: 1})
        .then(res => {
          window.location.href = `//${res.url}`;
        })
        .catch(catchAppError);
    },
    exportExcel() {
      const q = _.reduce(this.multipleSelection, (a, b) => _.concat(a, b), []);
      const idList = q.map(({id}) => id);
      const params = {
        isAll: 2,
        type: 5,
        idList: []
      };
      if (idList.length === this.specialItems.length) {
        params.isAll = 1;
      } else {
        params.idList = idList;
      }
      if (!params.idList.length && params.isAll === 2) {
        toast('导出表格勾选内容不能为空！');
        return;
      }
      http
        .post(url.exportExcel, params)
        .then(res => {
          window.location.href = `//${res.url}`;
        })
        .catch(catchAppError);
    },
    handleCurrentChange(val) {
      this.showSpecialItems = _.chunk(this.specialItems, this.pageSize)[
        val - 1
      ];
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.handleCurrentChange(1);
      this.multipleSelection = [];
    },
    getSpecialItems() {
      http
        .post(url.productList, this.params)
        .then(res => {
          this.specialItems = res;
          this.handleCurrentChange(1);
        })
        .catch(catchAppError);
    },
    filter(id) {
      this.params.grade_id = id;
      this.getSpecialItems();
    },
    handleDelete({id}) {
      this.$confirm('是否确定删除此项目?', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          http
            .post(url.deleteProduct, {commodity_id: id})
            .then(() => {
              toast('删除成功');
              this.getSpecialItems();
            })
            .catch(catchAppError);
        })
        .catch(() => {});
    },
    handleEdit(id) {
      menusNavigation.navTab('ProjectNew', '2', {id, nav: '2'});
    },
    upExcelSuccess(res) {
      if (res.code === 1) {
        this.$message({
          message: '文件导入成功',
          duration: 5000,
          type: 'success'
        });
        this.uniqueProject = _.uniqueId();
      } else {
        this.$message({
          message: res.msg,
          duration: 5000,
          type: 'error'
        });
      }
    },
    upExcelError() {
      this.$message({
        message: '文件导入失败',
        duration: 5000,
        type: 'error'
      });
    },
    upMassagetPrice() {
      const params = {
        data: this.showSpecialItems.map(({price, id}) => ({...price, id}))
      };
      http
        .post(url.upMassagetPrice, params)
        .then(() => {
          toast('信息修改成功！');
          changeEditStatus(false);
        })
        .catch(catchAppError);
    }
  }
};
</script>

<style lang="scss"></style>
